package com.greatwqs.wmall.common.provider.spring;

import com.greatwqs.wmall.common.module.constants.HttpHeaders;
import com.greatwqs.wmall.common.module.model.LoginUser;
import com.greatwqs.wmall.common.module.util.Base64Util;
import com.greatwqs.wmall.common.module.util.JsonUtil;

import lombok.extern.slf4j.Slf4j;

import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/***
 *
 * LoginUser 封装到 Controller 方法参数中：
 * 1. 带有 @Controller 或 @RestController 注解的类中的方法
 * 2. 通过 Spring MVC 请求映射（如 @GetMapping, @PostMapping 等）处理的方法参数
 *
 * @author wang-qingsong
 * @since 2025/03/27
 */
@Slf4j
@Component
public class LoginUserResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().equals(LoginUser.class);
    }

    @Override
    public Object resolveArgument(
            MethodParameter parameter,
            ModelAndViewContainer mavContainer,
            NativeWebRequest webRequest,
            WebDataBinderFactory binderFactory) throws Exception {
        final String userJson = Base64Util.decode(webRequest.getHeader(HttpHeaders.X_INTERNAL_USER));
        return JsonUtil.fromJson(userJson, LoginUser.class);
    }
}